package com.dgut.controller;

import com.dgut.pojo.Users;
import com.dgut.service.UserService;
import com.dgut.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@ResponseBody
public class UserController {

    @Resource
    private UserService userService;
    @RequestMapping(value = "login1",method = RequestMethod.POST)
    public ResultVO<Users> loginOut(String loginName, String password, HttpServletRequest request){
        int i = userService.login(loginName, password);
        if(i == 1){
            request.getSession().setAttribute("loginName",loginName);
            return new ResultVO<Users>();
        }else {
            return new ResultVO<Users>(500,"登陆失败！用户名或密码错误");
        }
    }

    /**
     * 从session拿到用户名称
     * @return
     */
    @RequestMapping(value = "getLoginName",method = RequestMethod.GET)
    public ResultVO<Users> getLoginName(HttpServletRequest request){
        String loginName = (String) request.getSession().getAttribute("loginName");
        return new ResultVO<>(loginName);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "loginOut",method = RequestMethod.GET)
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script> alert('退出成功！');top.location.href='login.html'</script>");
    }
}

